<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\Snotify;
use App\Extend\Phpoffice;
use App\Model\SaSmsNotify;
use App\Extend\ServerMonitor;
use App\Service\UploadService;

class IndexController extends BaseController
{
    /**
     * 获取服务器参数.
     */
    public function getServerMonitor()
    {
        $systemIns = new ServerMonitor();

        $data['runTime'] = $systemIns->getUpTime();            // 获取运行时间
        $data['memory']  = $systemIns->getMem(true);   // 获取内存信息
        $data['cpu']     = $systemIns->getCPU();               // 获取CPU使用率

        return successJson($data);
    }

    /**
     * 上传文件.
     */
    public function uploadFile()
    {
        $file = $this->requestFile['file'];

        return successJson(UploadService::file($file));
    }

    /**
     * 批量发送短信通知(使用队列).
     */
    public function batchSendNotify()
    {
        $excel  = $this->requestFile['excel'];
        $result = Phpoffice::import($excel);

        $data = [];
        foreach ($result as $key => $val) {
            if ($val[0]) {
                $info               = [];
                $info['value']      = $val[0];
                $info['status']     = 0;
                $data[]             = $info;
            }
        }
        SaSmsNotify::insert($data);

        SaSmsNotify::where('status', 0)->chunk(1000, function ($notifies) {
            // 待发送短信通知入队
            foreach ($notifies as $notify) {
                // dispatch 分发任务
                // delay    延迟2秒分发
                Snotify::dispatch($notify)->delay(now()->addSeconds(2));
            }
        });
        // php artisan queue:work   消费队列
        // 正式环境下，需要使用 Supervisor 进程守护

        return successJson();
    }
}
